package com.ff.kvm.mall.service.impl;

import com.ff.kvm.common.dv.shopping.ShoppingCartDV;
import com.ff.kvm.common.util.BeanConvertUtils;
import com.ff.kvm.common.util.Constants;
import com.ff.kvm.common.util.MyUtil;
import com.ff.kvm.mall.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class RedisServiceImpl implements RedisService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String getCache(String key) {
        if(MyUtil.isBlank(key)){
            return null;
        }
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj != null) {
            return obj.toString();
        }
        return null;
    }



    @Override
    public void putCache(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public void delCache(String key) {
        if(MyUtil.isBlank(key)){
            return ;
        }
        if (redisTemplate.hasKey(key).booleanValue()){
            redisTemplate.delete(key);
        }
    }

    @Override
    public ShoppingCartDV getShoppingCart(int userId) {
        String key = Constants.SHOPPINTG_CART+userId;
        if (redisTemplate.hasKey(key)){
            Object obj = redisTemplate.opsForValue().get(key);
            return BeanConvertUtils.convert(obj, ShoppingCartDV.class);
        }
        return null;
    }

    @Override
    public void putShoppingCart(ShoppingCartDV shoppingCartDV) {
        redisTemplate.opsForValue().set(Constants.SHOPPINTG_CART+shoppingCartDV.getUserId(), MyUtil.toJSON(shoppingCartDV));
    }

    @Override
    public void slo(String userId, String tokenId) {

        Object oldTokenId = redisTemplate.opsForValue().get(userId);
        if (oldTokenId != null && redisTemplate.hasKey(oldTokenId)) {
            redisTemplate.delete(oldTokenId);
        }
        redisTemplate.opsForValue().set(userId, tokenId);
        redisTemplate.expire(userId, 4, TimeUnit.HOURS);

        redisTemplate.opsForValue().set(tokenId, userId);
        redisTemplate.expire(tokenId, 4, TimeUnit.HOURS);
    }
}
